﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace Growatt.DuiHelpers
{
    /// <summary>
    /// json辅助类
    /// </summary>
    public class DuiHelperJson
    {
        /// <summary>
        /// 对象转换成json串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectToJson(object obj)
        {
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //MemoryStream stream = new MemoryStream();
            //serializer.WriteObject(stream, obj);
            //byte[] dataBytes = new byte[stream.Length];
            //stream.Position = 0;
            //stream.Read(dataBytes, 0, (int)stream.Length);
            //return Encoding.UTF8.GetString(dataBytes);
            string json = null;
            try
            {
                json = JsonConvert.SerializeObject(obj);
            }
            catch (Exception)
            {
            }

            return json;
        }

        /// <summary>
        /// 从一个Json串生成对象信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(string jsonString)
        {
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            //return (T)serializer.ReadObject(mStream);
            try
            {
                var value = JsonConvert.DeserializeObject<T>(jsonString);
                return value;
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }

        public static object JsonToObject(string jsonString, Type type)
        {
            //DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            //MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            //return (T)serializer.ReadObject(mStream);
            try
            {
                var value = JsonConvert.DeserializeObject(jsonString, type);
                return value;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 从一个Json串生成对象信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static object JsonToObject(string jsonString)
        {
            object obj = null;
            try
            {
                obj = JsonConvert.DeserializeObject(jsonString);
            }
            catch (Exception)
            {
            }

            return obj;
        }

        /// <summary>
        /// 写入对象(转换成json)到文件中，若追加则使用行号符分隔
        /// </summary>
        /// <param name="path"></param>
        /// <param name="obj"></param>
        /// <param name="isAppend"></param>
        /// <returns></returns>
        public static bool WriteFile(string path, object obj, bool isAppend = false)
        {
            if (obj == null)
                return false;
            var json = ObjectToJson(obj);
            return WriteFile(path, json, isAppend);
        }

        /// <summary>
        /// 写入json数据到文件中，若追加则使用行号符分隔
        /// </summary>
        /// <param name="path"></param>
        /// <param name="json"></param>
        /// <param name="isAppend">是否追加到文件末尾</param>
        /// <returns></returns>
        public static bool WriteFile(string path, string json, bool isAppend = false)
        {
            try
            {
                var dir = Path.GetDirectoryName(path);

                if (Directory.Exists(dir) == false)
                    Directory.CreateDirectory(dir);

                if (isAppend)
                {
                    json += Environment.NewLine;
                }

                var stream = File.Open(path, isAppend ? FileMode.Append : FileMode.Truncate);
                var sw = new StreamWriter(stream);
                sw.Write(json);
                sw.Close();
                stream.Close();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将json数据反序列化为Dictionary
        /// </summary>
        /// <param name="jsonData">json数据</param>
        /// <returns></returns>
        public static Dictionary<string, object> JsonToDictionary(string jsonData)
        {
            try
            {
                return JsonToObject<Dictionary<string, object>>(jsonData);
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}